package com.shenma2009.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenma2009.domain.ResultResponse;
import com.shenma2009.mapper.TbProductMapper;
import com.shenma2009.mapper.TbWareMapper;
import com.shenma2009.pojo.TbOrder;
import com.shenma2009.pojo.TbProduct;
import com.shenma2009.pojo.TbWare;
import com.shenma2009.service.TbOrderService;
import com.shenma2009.mapper.TbOrderMapper;
import com.shenma2009.service.TbProductService;
import com.shenma2009.utils.IdWorker;
import com.shenma2009.utils.RedissionLocker;
import com.shenma2009.utils.TokenUtils;
import com.shenma2009.vo.*;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 33509
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2023-04-25 16:29:24
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Autowired
    TbProductMapper tbProductMapper;

    @Autowired
    TbWareMapper tbWareMapper;

    @Resource
    private RedissonClient redisson;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Transactional(rollbackFor = Exception.class)
    public ResultResponse addOrder(Integer productId, Integer userId, String userName) {

        //--1 判断商品是否存在、上架
        TbProduct tbProduct = tbProductMapper.selectById(productId);
        if(tbProduct == null) {
            return ResultResponse.FAILED(404, "商品不存在");
        }

        //--2 判断库存
        QueryWrapper<TbWare> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbWare::getProductId, productId).last("limit 1");
        TbWare tbWare = tbWareMapper.selectOne(wrapper);
        if(tbWare == null || tbWare.getWareCount() <=0) {
            return ResultResponse.FAILED(404, "商品已售罄");
        }

        //--3 扣减库存
        tbWare.setWareCount(tbWare.getWareCount()-1);
        tbWare.setUpdateTime(null);
        tbWareMapper.updateById(tbWare);

        //--4 生成订单
        TbOrder tbOrder = new TbOrder();
        // 2023042516420001
        tbOrder.setOrderNo(IdWorker.getId());
        tbOrder.setOrderAmount(1);
        tbOrder.setProducId(tbProduct.getProductId());
        tbOrder.setProductCount(1);
        tbOrder.setProductName(tbProduct.getProductName());

        tbOrder.setUserId(userId);
        tbOrder.setUserName(userName);

        this.save(tbOrder);

        //--5

        return ResultResponse.SUCCESS(tbOrder.getOrderId());
    }

    @Override
    public boolean cancelOrder(Integer orderId) {

        RLock rLock = redisson.getLock("tb_ware_rollback");

        try {
            rLock.lock();

            return doCancelOrder(orderId);

        } finally {
            rLock.unlock();
        }
    }

    @Override
    public ResultResponse listByPage(PageVo pageVo) {

        Page<TbOrder> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());

        Page<TbOrder> tbOrderPage = this.page(page);

        List<TbOrderVo> collect = tbOrderPage.getRecords().stream().map(item -> {
            TbOrderVo tbOrderVo = new TbOrderVo();
            BeanUtils.copyProperties(item, tbOrderVo);
            tbOrderVo.setOrderNo(""+item.getOrderNo());
            return tbOrderVo;
        }).collect(Collectors.toList());

        Page<TbOrderVo> orderVoPage = new Page<>();
        BeanUtils.copyProperties(tbOrderPage, orderVoPage);
        orderVoPage.setRecords(collect);

        return ResultResponse.SUCCESS(orderVoPage);
    }

    @Override
    public ResultResponse payOrderOK(Integer orderId, String orderNo) {
        //-- 查询订单是否存在
        TbOrder tbOrder = this.getById(orderId);
        if(tbOrder == null) {
            return ResultResponse.FAILED(404, "订单不存在");
        }

        //-- 修改顶顶那状态
        tbOrder.setOrderState(1);
        tbOrder.setOrderNo(Long.valueOf(orderNo));
        tbOrder.setUpdateTime(null);

        updateById(tbOrder);

        return ResultResponse.SUCCESS();
    }

    @Transactional
    public boolean doCancelOrder(Integer orderId) {
        //-- 判断订单是否支付了
        TbOrder tbOrder = this.getById(orderId);
        if(tbOrder == null) {
            return false;
        }
        if(!tbOrder.getOrderState().equals(0)) {
            return false;
        }

        //-- 设置订单取消状态
        tbOrder.setOrderState(2);
        tbOrder.setUpdateTime(null);
        updateById(tbOrder);

        //-- 回归库存
        TbWare tbWare = tbWareMapper.selectOne(
                new QueryWrapper<TbWare>().lambda().eq(TbWare::getProductId, tbOrder.getProducId()).last("limit 1")
        );

        tbWare.setWareCount(tbWare.getWareCount()+tbOrder.getProductCount());
        tbWare.setUpdateTime(null);
        tbWareMapper.updateById(tbWare);

        return true;
    }

    @Override
    public ResultResponse add(IdVo idVo, String token) {


        //--2 token解析
        TokenUtils tokenUtils = TokenUtils.token();
        int result = tokenUtils.parseToken(token);
        if(result == 1 || result == 3) {
            return ResultResponse.FAILED(500, "token解析错误");
        }

        // 获取分布式锁
//        RedissonClient redissonClient = RedissionLocker.getRedissonClient();
        RLock rLock = redisson.getLock("tb_ware");
        ResultResponse resultResponse = null;
        Integer orderId = null;

        try {
            // 加锁
            rLock.lock();
            // 有事务管理
            resultResponse = addOrder(idVo.getId(), Integer.valueOf(tokenUtils.getClaim("userId")), tokenUtils.getClaim("userName"));
            orderId = (Integer)resultResponse.getData();


        } finally {
            // 释放锁
            rLock.unlock();
        }

        //
        //--
        rabbitTemplate.convertAndSend("orderExchange", "", ""+orderId);

        return resultResponse;
    }

    @Override
    public ResultResponse del(IdVo idVo) {
        TbOrder byId = this.getById(idVo.getId());
        if (byId == null){
            return ResultResponse.FAILED(404,"商品不存在");
        }
        this.removeById(idVo.getId());
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse set(TbOrderVo tbOrderVo) {
        TbOrder byId = this.getById(tbOrderVo.getOrderId());
        if (byId == null){
            return ResultResponse.FAILED(404,"商品不存在");
        }

        BeanUtils.copyProperties(tbOrderVo,byId);
        byId.setUpdateTime(null);
        this.updateById(byId);

        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse get(IdVo idVo) {
        TbOrder byId = this.getById(idVo.getId());
        if (byId == null){
            return ResultResponse.FAILED(404,"商品不存在");
        }
        return ResultResponse.SUCCESS(byId);
    }


}




